<?php

// 发立得信息发布系统房屋信息版(php+mysql) V1.0
// 演示地址: http://fang.chalide.cn
// 文件路径: usr/fabu.php
// 文件大小: 25799 字节
// 最后修改时间: 2025-05-23 21:05:12
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
/**
 * 本文件功能：发布信息
 * 版权声明：保留发行权和署名权
 * 作者信息：15058593138@qq.com
 */

// 获取当前用户
$curr_user = check_login(USER_TYPE_USER);
$db = DB::getInstance();

// 处理AJAX请求
if (isset($_GET['act'])) {
    $act = $_GET['act'];
    
    switch ($act) {
        // 发布信息
        case 'submit':
            if (empty($_POST['title']) || empty($_POST['type1']) || empty($_POST['type2']) || 
                empty($_POST['jiage']) || empty($_POST['cname']) || empty($_POST['cmobi'])) {
                json_msg(0, '请填写必填项');
            }
            
            $data = [
                'user_id' => $curr_user['id'],
                'title' => $db->escape($_POST['title']),
                'type1' => intval($_POST['type1']),
                'type2' => intval($_POST['type2']),
                'jiage' => intval($_POST['jiage']),
                'area' => isset($_POST['area']) ? floatval($_POST['area']) : 0,
                'desc' => isset($_POST['desc']) ? $db->escape($_POST['desc']) : '',
                'keys' => isset($_POST['keys']) ? $db->escape($_POST['keys']) : '',
                'cname' => $db->escape($_POST['cname']),
                'cmobi' => $db->escape($_POST['cmobi']),
                'addr' => isset($_POST['addr']) ? $db->escape($_POST['addr']) : '',
                'open1' => 1,
                'open2' => 1,
                'add_time' => date('Y-m-d H:i:s'),
                'gai_time' => date('Y-m-d H:i:s'),
                'view' => 0
            ];
            
            // 插入数据
            $infoId = $db->insert('info', $data);
            
            if (!$infoId) {
                json_msg(0, '发布失败，请稍后重试');
            }
            
            json_msg(1, '发布成功', ['id' => $infoId]);
            break;
            
        // 上传图片
        case 'upload':
            if (empty($_GET['id'])) {
                json_msg(0, '参数错误');
            }
            
            $infoId = intval($_GET['id']);
            
            // 检查信息是否存在且属于当前用户
            $sql = "SELECT id FROM info WHERE id = $infoId AND user_id = {$curr_user['id']}";
            $info = $db->getRow($sql);
            
            if (!$info) {
                json_msg(0, '信息不存在');
            }
            
            // 检查上传文件
            if (empty($_FILES['file']) || $_FILES['file']['error'] != 0) {
                json_msg(0, '上传失败，请重试');
            }
            
            // 检查文件类型
            $allow_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
            if (!in_array($_FILES['file']['type'], $allow_types)) {
                json_msg(0, '只允许上传jpg、png、gif格式的图片');
            }
            
            // 检查文件大小
            if ($_FILES['file']['size'] > $CONFIG['upload_max_size']) {
                json_msg(0, '图片大小不能超过' . ($CONFIG['upload_max_size'] / 1024 / 1024) . 'MB');
            }
            
            // 生成保存路径
            $dir = 'imgs/' . date('Y/m/d');
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            
            $filename = date('YmdHis') . random_str() . '.jpg';
            $path = $dir . '/' . $filename;
            
            // 保存文件
            if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
                // 插入图片记录
                $data = [
                    'info_id' => $infoId,
                    'path' => $path,
                    'sort' => 0,
                    'add_time' => date('Y-m-d H:i:s')
                ];
                
                $imgId = $db->insert('imgs', $data);
                
                if ($imgId) {
                    json_msg(1, '上传成功', ['id' => $imgId, 'path' => $path]);
                } else {
                    json_msg(0, '保存记录失败');
                }
            } else {
                json_msg(0, '保存文件失败');
            }
            break;
            
        // 加载关键词
        case 'keys':
            // 读取关键词列表
            $keys_file = './inc/keys.json';
            if (file_exists($keys_file)) {
                $keys_json = file_get_contents($keys_file);
                $keys_arr = json_decode($keys_json, true);
                json_msg(1, '获取成功', $keys_arr);
            } else {
                json_msg(0, '关键词列表不存在');
            }
            break;
            
        default:
            json_msg(0, '未知操作');
    }
    
    exit;
}

include './inc/head.php';
// 获取用户上次发布的联系方式
$last_info = $db->getRow("SELECT cname, cmobi FROM info WHERE user_id = {$curr_user['id']} ORDER BY id DESC LIMIT 1");
?>

<div class="fabu-container" style="background:#fff;padding:20px;border-radius:5px;box-shadow:0 1px 3px rgba(0,0,0,0.1);">
    <h2 style="margin-bottom:20px;">发布信息</h2>
    
    <form id="fabu-form">
        <div class="form-group">
            <label class="form-label">标题 <span style="color:red;">*</span></label>
            <input type="text" name="title" class="form-control" placeholder="请输入标题" required>
        </div>
        
        <div class="form-group">
            <label class="form-label">信息类型 <span style="color:red;">*</span></label>
            <select name="type1" class="form-control" required>
                <option value="">请选择信息类型</option>
                <?php
                // 获取信息类型
                $type1_file = './inc/type1.json';
                if (file_exists($type1_file)) {
                    $type1_json = file_get_contents($type1_file);
                    $type1_arr = json_decode($type1_json, true);
                    foreach ($type1_arr as $code => $name) {
                        echo "<option value=\"$code\">$name</option>";
                    }
                }
                ?>
            </select>
        </div>
        
        <div class="form-group">
            <label class="form-label">交易类型 <span style="color:red;">*</span></label>
            <select name="type2" class="form-control" required>
                <option value="">请选择交易类型</option>
                <?php
                // 获取交易类型
                $type2_file = './inc/type2.json';
                if (file_exists($type2_file)) {
                    $type2_json = file_get_contents($type2_file);
                    $type2_arr = json_decode($type2_json, true);
                    foreach ($type2_arr as $code => $name) {
                        echo "<option value=\"$code\">$name</option>";
                    }
                }
                ?>
            </select>
        </div>
        
        <div class="form-group">
            <label class="form-label">价格 <span style="color:red;">*</span></label>
            <input type="number" name="jiage" class="form-control" placeholder="请输入价格" required>
        </div>
        
        <div class="form-group">
            <label class="form-label">面积</label>
            <input type="number" name="area" class="form-control" placeholder="请输入面积（平方米）" step="0.01">
        </div>
        
        <div class="form-group">
            <label class="form-label">关键词</label>
            <div class="keys-container" style="margin-bottom:10px;">
                <input type="text" name="keys_input" class="form-control" placeholder="输入关键词，多个关键词用逗号分隔">
                <button type="button" id="select-keys-btn" class="btn btn-default" style="margin-top:10px;">选择关键词</button>
            </div>
            <div id="selected-keys" style="margin-top:10px;"></div>
            <input type="hidden" name="keys">
        </div>
        
        <div class="form-group">
            <label class="form-label">详细描述</label>
            <textarea name="desc" class="form-control" rows="5" placeholder="请输入详细描述"></textarea>
        </div>
        
        <div class="form-group">
            <label class="form-label">详细地址</label>
            <div style="display:flex;margin-bottom:10px;">
                <select id="county" class="form-control" style="width:50%;margin-right:10px;">
                    <option value="">请选择区县</option>
                    <?php
                    // 获取区县列表
                    $area_file = './inc/area.json'; // 默认杭州
                    if (file_exists($area_file)) {
                        $area_json = file_get_contents($area_file);
                        $area_arr = json_decode($area_json, true);
                        foreach ($area_arr as $code => $name) {
                            echo "<option value=\"$code\">$name</option>";
                        }
                    }
                    ?>
                </select>
                <select id="town" class="form-control" style="width:50%;display:none;">
                    <option value="">请先选择区县</option>
                </select>
            </div>
            <input type="text" name="addr" class="form-control" placeholder="请输入详细地址">
        </div>
        
        <div class="form-group">
            <label class="form-label">联系人 <span style="color:red;">*</span></label>
            <input type="text" name="cname" class="form-control" placeholder="请输入联系人姓名" 
                   value="<?php echo isset($last_info['cname']) ? $last_info['cname'] : ''; ?>" required>
        </div>
        
        <div class="form-group">
            <label class="form-label">联系电话 <span style="color:red;">*</span></label>
            <input type="tel" name="cmobi" class="form-control" placeholder="请输入联系电话" 
                   value="<?php echo isset($last_info['cmobi']) ? $last_info['cmobi'] : $curr_user['mobi']; ?>" required>
        </div>
        
        <div class="form-group">
            <button type="button" id="submit-btn" class="btn btn-primary">提交发布</button>
        </div>
    </form>
</div>

<!-- 关键词选择模态框 -->
<div id="keys-modal" style="display:none;">
    <div id="keys-list" style="display:flex;flex-wrap:wrap;"></div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const submitBtn = document.getElementById('submit-btn');
    const fabuForm = document.getElementById('fabu-form');
    const selectKeysBtn = document.getElementById('select-keys-btn');
    const selectedKeysDiv = document.getElementById('selected-keys');
    const keysInput = fabuForm.elements.keys_input;
    const keysHidden = fabuForm.elements.keys;
    let keysArray = [];
    
    // 加载关键词列表
    function loadKeys() {
        ajax({
            url: 'usr.php?do=fabu&act=keys',
            method: 'POST',
            success: function(res) {
                if (res.code === 1) {
                    window.keysList = res.data;
                } else {
                    showToast(res.msg);
                }
            }
        });
    }
    
    // 初始加载关键词
    loadKeys();
    
    // 更新已选关键词显示
    function updateSelectedKeys() {
        selectedKeysDiv.innerHTML = '';
        keysHidden.value = keysArray.join(',');
        
        if (keysArray.length === 0) {
            return;
        }
        
        let html = '';
        for (let i = 0; i < keysArray.length; i++) {
            html += '<span style="display:inline-block;margin:3px 5px;padding:3px 10px;background:#e1e1e1;border-radius:3px;">' + 
                    keysArray[i] + 
                    '<a href="javascript:;" class="remove-key" data-index="' + i + '" style="margin-left:5px;color:red;">×</a></span>';
        }
        
        selectedKeysDiv.innerHTML = html;
        
        // 绑定删除事件
        const removeLinks = document.querySelectorAll('.remove-key');
        for (let i = 0; i < removeLinks.length; i++) {
            removeLinks[i].addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                keysArray.splice(index, 1);
                updateSelectedKeys();
            });
        }
    }
    
    // 处理关键词输入框的变化
    keysInput.addEventListener('change', function() {
        const value = this.value.trim();
        if (value) {
            const keys = value.split(',');
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i].trim();
                if (key && keysArray.indexOf(key) === -1 && keysArray.length < 20) {
                    keysArray.push(key);
                }
            }
            this.value = '';
            updateSelectedKeys();
        }
    });
    
    // 选择关键词按钮点击事件
    selectKeysBtn.addEventListener('click', function() {
        if (!window.keysList) {
            showToast('关键词列表加载中，请稍后重试');
            return;
        }
        
        let html = '';
        for (let i = 0; i < window.keysList.length; i++) {
            const key = window.keysList[i];
            const selected = keysArray.indexOf(key) !== -1;
            html += '<div style="margin:5px;"><label style="display:block;padding:8px 15px;background:' + (selected ? '#0066cc' : '#f5f5f5') + ';color:' + (selected ? '#fff' : '#333') + ';border-radius:3px;cursor:pointer;">' +
                    '<input type="checkbox" value="' + key + '" ' + (selected ? 'checked' : '') + ' style="margin-right:5px;">' + key +
                    '</label></div>';
        }
        
        const modal = showModal('选择关键词', '<div id="keys-list" style="display:flex;flex-wrap:wrap;">' + html + '</div>', [
            {
                text: '确定',
                class: 'btn btn-primary',
                onClick: function() {
                    keysArray = [];
                    const checks = document.querySelectorAll('#keys-list input:checked');
                    for (let i = 0; i < checks.length; i++) {
                        if (keysArray.length < 20) {
                            keysArray.push(checks[i].value);
                        }
                    }
                    updateSelectedKeys();
                    // 关闭模态框
                    const mask = document.querySelector('.mask');
                    if (mask) {
                        document.body.removeChild(mask);
                    }
                }
            }
        ]);
        
        // 绑定选择事件
        const checks = document.querySelectorAll('#keys-list input');
        for (let i = 0; i < checks.length; i++) {
            checks[i].addEventListener('change', function() {
                const label = this.parentNode;
                if (this.checked) {
                    label.style.background = '#0066cc';
                    label.style.color = '#fff';
                } else {
                    label.style.background = '#f5f5f5';
                    label.style.color = '#333';
                }
            });
        }
    });
    
    // 提交按钮点击事件
    submitBtn.addEventListener('click', function() {
        const title = fabuForm.elements.title.value;
        const type1 = fabuForm.elements.type1.value;
        const type2 = fabuForm.elements.type2.value;
        const jiage = fabuForm.elements.jiage.value;
        const cname = fabuForm.elements.cname.value;
        const cmobi = fabuForm.elements.cmobi.value;
        
        if (!title) {
            showToast('请输入标题');
            return;
        }
        
        if (!type1) {
            showToast('请选择信息类型');
            return;
        }
        
        if (!type2) {
            showToast('请选择交易类型');
            return;
        }
        
        if (!jiage) {
            showToast('请输入价格');
            return;
        }
        
        if (!cname) {
            showToast('请输入联系人');
            return;
        }
        
        if (!cmobi) {
            showToast('请输入联系电话');
            return;
        }
        
        // 构建详细地址
        const county = document.getElementById('county');
        const town = document.getElementById('town');
        let addrPrefix = '';
        
        if (county.value) {
            addrPrefix += county.options[county.selectedIndex].text;
        }
        
        if (town.value) {
            addrPrefix += town.options[town.selectedIndex].text;
        }
        
        if (addrPrefix && fabuForm.elements.addr.value) {
            fabuForm.elements.addr.value = addrPrefix + ' ' + fabuForm.elements.addr.value;
        }
        
        // 提交发布
        ajax({
            url: 'usr.php?do=fabu&act=submit',
            method: 'POST',
            data: {
                title: title,
                type1: type1,
                type2: type2,
                jiage: jiage,
                area: fabuForm.elements.area.value,
                desc: fabuForm.elements.desc.value,
                keys: keysHidden.value,
                cname: cname,
                cmobi: cmobi,
                addr: fabuForm.elements.addr.value
            },
            success: function(res) {
                showToast(res.msg);
                if (res.code === 1) {
                    // 发布成功，显示上传图片界面
                    showUploadImages(res.data.id);
                }
            },
            error: function() {
                showToast('网络错误，请稍后重试');
            }
        });
    });
    
    // 显示上传图片界面
    function showUploadImages(infoId) {
        let html = '<div class="upload-container">';
        html += '<p>您可以上传0-5张图片</p>';
        html += '<div class="upload-area" style="border:2px dashed #ddd;padding:20px;text-align:center;margin:15px 0;cursor:pointer;">';
        html += '点击或拖拽图片到此处上传';
        html += '</div>';
        html += '<div class="image-list" style="display:flex;flex-wrap:wrap;"></div>';
        html += '</div>';
        
        const modal = showModal('上传图片', html, [
            {
                text: '跳过',
                class: 'btn btn-default',
                onClick: function() {
                    // 关闭模态框
                    const mask = document.querySelector('.mask');
                    if (mask) {
                        document.body.removeChild(mask);
                    }
                    showToast('发布成功');
                    setTimeout(function() {
                        window.location.href = 'usr.php?do=list';
                    }, 1000);
                }
            },
            {
                text: '完成',
                class: 'btn btn-primary',
                onClick: function() {
                    // 关闭模态框
                    const mask = document.querySelector('.mask');
                    if (mask) {
                        document.body.removeChild(mask);
                    }
                    showToast('发布成功');
                    setTimeout(function() {
                        window.location.href = 'usr.php?do=list';
                    }, 1000);
                }
            }
        ]);
        
        // 上传区域点击事件
        const uploadArea = document.querySelector('.upload-area');
        const imageList = document.querySelector('.image-list');
        let uploadCount = 0;
        
        // 创建隐藏的文件输入
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = 'image/*';
        fileInput.style.display = 'none';
        document.body.appendChild(fileInput);
        
        // 点击上传区域
        uploadArea.addEventListener('click', function() {
            if (uploadCount >= 5) {
                showToast('最多上传5张图片');
                return;
            }
            fileInput.click();
        });
        
        // 文件选择变化
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                uploadImage(this.files[0], infoId);
                this.value = ''; // 清空，允许再次选择相同文件
            }
        });
        
        // 上传图片
        function uploadImage(file, infoId) {
            if (uploadCount >= 5) {
                showToast('最多上传5张图片');
                return;
            }
            
            // 添加预览
            const reader = new FileReader();
            reader.onload = function(e) {
                const previewDiv = document.createElement('div');
                previewDiv.className = 'image-item';
                previewDiv.style.position = 'relative';
                previewDiv.style.width = '120px';
                previewDiv.style.height = '120px';
                previewDiv.style.margin = '5px';
                previewDiv.style.border = '1px solid #ddd';
                previewDiv.style.overflow = 'hidden';
                
                const img = document.createElement('img');
                img.src = e.target.result;
                img.style.width = '100%';
                img.style.height = '100%';
                img.style.objectFit = 'cover';
                
                const loadingDiv = document.createElement('div');
                loadingDiv.className = 'loading';
                loadingDiv.style.position = 'absolute';
                loadingDiv.style.top = '0';
                loadingDiv.style.left = '0';
                loadingDiv.style.width = '100%';
                loadingDiv.style.height = '100%';
                loadingDiv.style.background = 'rgba(0,0,0,0.5)';
                loadingDiv.style.color = '#fff';
                loadingDiv.style.display = 'flex';
                loadingDiv.style.justifyContent = 'center';
                loadingDiv.style.alignItems = 'center';
                loadingDiv.textContent = '上传中...';
                
                previewDiv.appendChild(img);
                previewDiv.appendChild(loadingDiv);
                imageList.appendChild(previewDiv);
                
                // 压缩图片并上传
                compressImage(file, function(blob) {
                    const formData = new FormData();
                    formData.append('file', blob);
                    
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', 'usr.php?do=fabu&act=upload&id=' + infoId, true);
                    
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === 4) {
                            if (xhr.status === 200) {
                                try {
                                    const res = JSON.parse(xhr.responseText);
                                    if (res.code === 1) {
                                        // 上传成功
                                        loadingDiv.style.background = 'rgba(0,0,0,0.3)';
                                        loadingDiv.innerHTML = '<div style="text-align:center;">上传成功<br><a href="javascript:;" class="delete-img" data-id="' + res.data.id + '" style="color:#fff;text-decoration:underline;">删除</a></div>';
                                        
                                        // 绑定删除事件
                                        const deleteLink = loadingDiv.querySelector('.delete-img');
                                        deleteLink.addEventListener('click', function() {
                                            const imgId = this.getAttribute('data-id');
                                            // 这里可以添加删除图片的AJAX请求
                                            previewDiv.remove();
                                            uploadCount--;
                                        });
                                        
                                        uploadCount++;
                                    } else {
                                        loadingDiv.textContent = '上传失败: ' + res.msg;
                                    }
                                } catch (e) {
                                    loadingDiv.textContent = '解析响应失败';
                                }
                            } else {
                                loadingDiv.textContent = '上传失败';
                            }
                        }
                    };
                    
                    xhr.send(formData);
                });
            };
            
            reader.readAsDataURL(file);
        }
        
        // 拖拽上传
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.background = '#f5f5f5';
        });
        
        uploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.style.background = 'transparent';
        });
        
        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.background = 'transparent';
            
            if (e.dataTransfer.files.length > 0) {
                uploadImage(e.dataTransfer.files[0], infoId);
            }
        });
    }
});
</script>
